package com.ymy.cloud.alibaba.seata.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ymy.cloud.alibaba.seata.order.entity.Order;
import com.ymy.cloud.alibaba.seata.order.feign.apis.StockClient;
import com.ymy.cloud.alibaba.seata.order.mapper.OrderMapper;
import com.ymy.cloud.alibaba.seata.order.service.OrderService;
import com.ymy.cloud.alibaba.seata.stock.entity.Stock;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Ringo
 * @date 2021/10/9
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
        implements OrderService {

    @Autowired
    private StockClient stockClient;

    @Resource
    private OrderMapper orderMapper;

    @Override
    @GlobalTransactional(name = "createOrder", rollbackFor = RuntimeException.class)
    public String create(Order order) {
        Integer productId = order.getProductId();
        Integer amount = order.getTotalAmount();

        // 根据 productId 查库存, 确定数量是否够?
        Stock stock = stockClient.getStock(productId);
        if (stock == null || stock.getCount() < amount) {
            throw new RuntimeException("库存不够！");
        }

        // 新增订单
        orderMapper.insert(order);

//        int i = 1 / 0;

        // 减库存
        stockClient.reduceStock(productId, amount);
        return "下单成功";
    }
}




